// coding: utf-8
// @Author : lryself
// @Date : 2021/5/20 14:02
// @Software: GoLand

package aliyunOSS

import (
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

type OssClient struct {
	Endpoint string
	AccessKeyId string
	AccessKeySecret string
	ReadWriteTimeout int64
	HttpConnectTimeout int64
}

func (c OssClient) makeClient() (*oss.Client, error) {
	client, err := oss.New(
		c.Endpoint, c.AccessKeyId, c.AccessKeySecret,
		oss.Timeout(c.HttpConnectTimeout, c.ReadWriteTimeout),
		)
	if err != nil {
		return nil, err
	}
	return client, nil
}

func (c OssClient) UpdateFile(bucketName, objectName, localFileName string) error {
	var err error
	client,err := c.makeClient()
	if err != nil {
		return err
	}
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return err
	}
	// 上传文件
	err = bucket.PutObjectFromFile(objectName, localFileName)
	if err != nil {
		return err
	}
	return nil
}

func (c OssClient) DownloadFile(bucketName, objectName, downloadedFileName string) error {
	var err error
	client,err := c.makeClient()
	if err != nil {
		return err
	}
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return err
	}
	// 上传文件
	err = bucket.GetObjectToFile(objectName, downloadedFileName)
	if err != nil {
		return err
	}
	return nil
}

func (c OssClient) DeleteFile(bucketName, objectName string) error {
	var err error
	client,err := c.makeClient()
	if err != nil {
		return err
	}
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return err
	}
	// 删除文件
	err = bucket.DeleteObject(objectName)
	if err != nil {
		return err
	}
	return nil
}

func (c OssClient) GetFileList(bucketName string) ([]string,error) {
	var err error
	client,err := c.makeClient()
	if err != nil {
		return nil,err
	}
	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return nil,err
	}

	keyList := []string{}
	marker := ""
	for {
		lsRes, err := bucket.ListObjects(oss.Marker(marker))
		if err != nil {
			return nil,err
		}
		// 打印列举文件，默认情况下一次返回100条记录。
		for _, object := range lsRes.Objects {
			keyList = append(keyList, object.Key)
		}
		if lsRes.IsTruncated {
			marker = lsRes.NextMarker
		} else {
			break
		}
	}
	return keyList,nil
}
